﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Scheduler;

namespace Angerona
{
    public partial class ModUser : PhoneApplicationPage
    {

        IsolatedStorageSettings userdata = IsolatedStorageSettings.ApplicationSettings;
        DateTime defaultdate = new DateTime(2013, 1, 1);
        public ModUser()
        {
            InitializeComponent();
            ApplicationBarInitializer();
            ReadingUserData();
            this.licenseexpire.ValueChanged += new EventHandler<DateTimeValueChangedEventArgs>(picker_ValueChanged);
            

        }

        /// <summary>
        /// Crea l'ApplicationBar localizzata
        /// Create the localized ApplicationBar
        /// </summary>
        private void ApplicationBarInitializer()
        {
            ApplicationBar = new ApplicationBar();
            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 1.0;
            ApplicationBar.IsVisible = true;
            ApplicationBar.IsMenuEnabled = false;

            // edit button
            ApplicationBarIconButton btn_save = new ApplicationBarIconButton();
            btn_save.IconUri = new Uri("/Img/appbar_save.png", UriKind.Relative);
            btn_save.Text = AngeronaLang.save;
            ApplicationBar.Buttons.Add(btn_save);
            btn_save.Click += new EventHandler(btn_save_Click);

            // undo button
            ApplicationBarIconButton btn_undo = new ApplicationBarIconButton();
            btn_undo.IconUri = new Uri("/Img/appbar_cancel.png", UriKind.Relative);
            btn_undo.Text = AngeronaLang.undo;
            ApplicationBar.Buttons.Add(btn_undo);
            btn_undo.Click += new EventHandler(btn_undo_Click);
        }

        /// <summary>
        /// Legge i dati dai setting relativi all'utente
        /// Aggiorna i campi con i dati dell'utente
        /// Refresh the user data displayed
        /// </summary>
        private void ReadingUserData()
        {
            //reading name
            uname.Text = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains("uname"))
                uname.Text = IsolatedStorageSettings.ApplicationSettings["uname"] as string;

            //reading surname
            usurname.Text = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains("usurname"))
                usurname.Text = IsolatedStorageSettings.ApplicationSettings["usurname"] as string;
           
            //reading License Number
            licensenum.Text = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains("licensenum"))
                licensenum.Text = IsolatedStorageSettings.ApplicationSettings["licensenum"] as string;

            //reading License Point
            licensepoint.Text = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains("licensepoint"))
                licensepoint.Text = IsolatedStorageSettings.ApplicationSettings["licensepoint"] as string;

            //reading License Release
            licenserelease.Value = defaultdate;
            if (IsolatedStorageSettings.ApplicationSettings.Contains("licenserelease"))
                licenserelease.Value = (DateTime)IsolatedStorageSettings.ApplicationSettings["licenserelease"];

            //reading License Expire
            licenseexpire.Value = defaultdate;
            if (IsolatedStorageSettings.ApplicationSettings.Contains("licenseexpire"))
                licenseexpire.Value = (DateTime)IsolatedStorageSettings.ApplicationSettings["licenseexpire"];

            //reading License Category
            licensecategory.Text = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains("licensecategory"))
                licensecategory.Text = IsolatedStorageSettings.ApplicationSettings["licensecategory"] as string;

            //reading License Restriction
            licenserextriction.Text = "";
            if (IsolatedStorageSettings.ApplicationSettings.Contains("licenserextriction"))
                licenserextriction.Text = IsolatedStorageSettings.ApplicationSettings["licenserextriction"] as string;
        }

        /// <summary>
        /// Handler del bottone salva
        /// Handler of delete save
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_save_Click(object sender, EventArgs e)
        {
            //add or update name        
            if (!userdata.Contains("uname"))
                userdata.Add("uname", uname.Text);
            else
                userdata["uname"] = uname.Text;

            //add or update surname         
            if (!userdata.Contains("usurname"))
                userdata.Add("usurname", usurname.Text);
            else
                userdata["usurname"] = usurname.Text;

            //add or update license number         
            if (!userdata.Contains("licensenum"))
                userdata.Add("licensenum", licensenum.Text);
            else
                userdata["licensenum"] = licensenum.Text;

            //add or update license point         
            if (!userdata.Contains("licensepoint"))
                userdata.Add("licensepoint", licensepoint.Text);
            else
                userdata["licensepoint"] = licensepoint.Text;

            //add or update license release         
            if (!userdata.Contains("licenserelease"))
                userdata.Add("licenserelease", licenserelease.Value);
            else
                userdata["licenserelease"] = (DateTime) licenserelease.Value;

            //add or update license expiration
            if (!userdata.Contains("licenseexpire"))
                userdata.Add("licenseexpire", licenseexpire.Value);
            else
                userdata["licenseexpire"] = (DateTime)licenseexpire.Value;
      
            //add or update license category         
            if (!userdata.Contains("licensecategory"))
                userdata.Add("licensecategory", licensecategory.Text);
            else
                userdata["licensecategory"] = licensecategory.Text;

            //add or update license restriction         
            if (!userdata.Contains("licenserextriction"))
                userdata.Add("licenserextriction", licenserextriction.Text);
            else
                userdata["licenserextriction"] = licenserextriction.Text;

            
            userdata.Save(); //SAVING
            SetExpirationReminder();

            NavigationService.GoBack(); //go back after saving
        }
        

        /// <summary>
        /// Handler for license expire value change, prevent the entering of passed date
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void picker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            if (licenseexpire.Value < DateTime.Now & licenseexpire.Value != defaultdate)
            {
                licenseexpire.Value = defaultdate;
                MessageBox.Show(AngeronaLang.ReminderErrorDate, AngeronaLang.Error, MessageBoxButton.OK);
            }

        }

        /// <summary>
        /// Set the reminder for the license expiration
        /// </summary>
        private void SetExpirationReminder()
        {
            
            if (IsolatedStorageSettings.ApplicationSettings.Contains("licenseexpire"))
                if ((DateTime)IsolatedStorageSettings.ApplicationSettings["licenseexpire"] != defaultdate)
                {
                    DateTime ExpirationDate = (DateTime)IsolatedStorageSettings.ApplicationSettings["licenseexpire"];
                    //MessageBox.Show(ExpirationDate.ToString(), "ExpirationDate", MessageBoxButton.OK); //TEST
                    //Delete a previous reminder, only if is same reminder
                    ScheduledAction OldReminder = ScheduledActionService.Find("LicenseExpired");
                    if (OldReminder != null)
                        ScheduledActionService.Remove(OldReminder.Name);

                    //Create the reminder
                    Reminder LicenseExpiredReminder = new Reminder("LicenseExpired")
                    {
                        BeginTime = ExpirationDate.AddHours(9),
                        Title = AngeronaLang.licenseReminderTitle,
                        Content = AngeronaLang.licenseReminderContenent,

                        //when a user interact with the reminder the App will open on User view
                        NavigationUri = new Uri("/Views/User.xaml", UriKind.Relative), 
                        
                    };
                    ScheduledActionService.Add(LicenseExpiredReminder);
                }
      
        }

        /// <summary>
        /// Handler del bottone annulla
        /// Handler of delete undo
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_undo_Click(object sender, EventArgs e)
        {
            //go back without saving
            NavigationService.GoBack();
        }
    }

}